package chat

import (
	"fmt"
	"io"
	"log"

	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/libp2p/go-libp2p"
	"github.com/libp2p/go-libp2p/core/crypto"
	"github.com/libp2p/go-libp2p/core/host"
)

// 创建主机地址
//
//	port	端口号
//	rdom	随机数的IO读操作
func makeHost(port int, rdom io.Reader) (host.Host, error) {
	// 创建私钥密钥对
	prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, rdom)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	ks, _ := prvKey.Raw()
	ps, _ := prvKey.GetPublic().Raw()
	fmt.Println("私钥：", xstring.BaseByte64Raw(ks))
	fmt.Println("公钥：", xstring.BaseByte64Raw(ps))

	// 0.0.0.0 监听任意来源IP
	// sourceMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port))
	// sourceMultiAddrUpd, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/0.0.0.0/udp/%d/quic", port))

	// libp2p.New 构造一个新的libp2p主机。可以在此处添加其他选项。
	return libp2p.New(
		libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/0.0.0.0/udp/%d/quic-v1", port),
			fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port),
			fmt.Sprintf("/ip6/::/tcp/%d", port),
		),
		// libp2p.ListenAddrs(sourceMultiAddr),
		// libp2p.ListenAddrs(sourceMultiAddrUpd),
		libp2p.Identity(prvKey),
	)
}
